// 内容脚本
console.log('自动登录助手内容脚本已加载');

// 检查是否启用了二维码功能
let qrCodeEnabled = true;
let qrCodeInitialized = false;

// 立即注入脚本到页面，不等待DOM完成
function injectScript() {
  const script = document.createElement('script');
  script.src = chrome.runtime.getURL('injected.js');
  script.onload = function() {
    this.remove();
  };
  (document.head || document.documentElement).appendChild(script);
}

// 注入二维码功能
function injectQRCodeScript() {
  if (!qrCodeEnabled || qrCodeInitialized) return;
  
  // 先注入qrcode.min.js库到页面
  const qrcodeLib = document.createElement('script');
  qrcodeLib.src = chrome.runtime.getURL('qrcode.min.js');
  qrcodeLib.onload = function() {
    console.log('二维码库已注入到页面');
    
    // 然后注入二维码功能脚本
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('qrcode-injector.js');
    script.onload = function() {
      console.log('二维码注入脚本已加载');
      qrCodeInitialized = true;
    };
    script.onerror = function() {
      console.error('二维码注入脚本加载失败');
    };
    (document.head || document.documentElement).appendChild(script);
  };
  qrcodeLib.onerror = function() {
    console.error('二维码库加载失败');
  };
  (document.head || document.documentElement).appendChild(qrcodeLib);
}

// 初始化二维码功能（检查设置）
function initQRCodeFeature() {
  chrome.storage.local.get(['enableQrCodeFeature'], function(result) {
    qrCodeEnabled = result.enableQrCodeFeature !== undefined ? result.enableQrCodeFeature : true;
    console.log('初始化二维码功能状态:', qrCodeEnabled);
    
    if (qrCodeEnabled) {
      injectQRCodeScript();
    }
  });
}

// 立即注入主脚本
injectScript();

// 初始化二维码功能
initQRCodeFeature();

// 监听来自background的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'loginSuccess') {
    console.log('收到登录成功消息:', request);
    
    // 等待页面中的登录表单数据
    setTimeout(() => {
      window.postMessage({
        action: 'getLoginFormData',
        domain: request.domain
      }, '*');
    }, 1000);
    
  } else if (request.action === 'checkLoginStatus') {
    console.log('检查登录状态:', request.account);
    
    // 发送检查登录状态消息到页面
    window.postMessage({
      action: 'checkLoginStatus',
      account: request.account,
      originUrl: request.originUrl
    }, '*');
    
  } else if (request.action === 'autoLogin') {
    console.log('开始自动登录:', request.account);
    
    // 发送自动登录消息到页面
    window.postMessage({
      action: 'performAutoLogin',
      account: request.account
    }, '*');
  } else if (request.action === 'toggleQRCode') {
    console.log('切换二维码功能:', request.enabled);
    qrCodeEnabled = request.enabled;
    
    if (qrCodeEnabled) {
      // 启用二维码功能
      if (!qrCodeInitialized) {
        injectQRCodeScript();
      } else {
        // 如果已经注入过，通知页面重新显示
        window.postMessage({
          action: 'enableQRCode'
        }, '*');
      }
    } else {
      // 禁用二维码功能
      if (qrCodeInitialized && window.qrCodeShareAPI) {
        window.qrCodeShareAPI.destroy();
      }
      
      // 通知页面移除二维码组件
      window.postMessage({
        action: 'disableQRCode'
      }, '*');
    }
  } else if (request.action === 'getUIdToken') {
    // 获取当前域名的uIdToken
    const hostname = request.hostname || window.location.hostname;
    console.log('获取uIdToken请求:', hostname);
    
    chrome.storage.local.get(['uIdToken'], function(result) {
      const tokens = result.uIdToken || {};
      const token = tokens[hostname];
      console.log('找到的uIdToken:', token);
      
      // 发送响应
      sendResponse({
        success: true,
        token: token,
        hostname: hostname
      });
    });
    
    return true; // 保持消息通道开放以便异步响应
  }
});

// 监听来自页面的消息
window.addEventListener('message', function(event) {
  if (event.source !== window) return;
  
  const message = event.data;
  if (!message || typeof message !== 'object') return;
  
  if (message.action === 'saveLoginInfo') {
    console.log('保存登录信息:', message);
    
    const {loginId, password, domain, hostname} = message;
    
    // 验证必要字段，防止保存undefined值
    if (!loginId || !password) {
      console.warn('登录信息不完整，跳过保存:', { loginId, password, domain, hostname });
      return;
    }
    
    // 确保domain和hostname有有效值
    const validDomain = domain || 'unknown';
    const validHostname = hostname || window.location.hostname || 'unknown';
    
    // 如果domain是'unknown'但hostname有效，使用hostname作为domain
    const finalDomain = validDomain === 'unknown' && validHostname !== 'unknown' ? validHostname : validDomain;
    
    const accountData = {
      loginId: loginId,
      password: password,
      domain: finalDomain,
      hostname: validHostname,
      origin: window.location.origin,
      saveTime: new Date().toISOString(),
      isDefault: false,
      alias: ''
    };
    
    console.log('处理后的账号数据:', accountData);
    
    // 保存到chrome.storage
    chrome.storage.local.get([hostname], function(result) {
      let accounts = result[hostname] || [];
      
      // 检查是否已存在相同的loginId
      const existingIndex = accounts.findIndex(acc => acc.loginId === loginId && acc.domain === domain);
      if (existingIndex !== -1) {
        // 更新现有账号，但保留现有的别名
        accounts[existingIndex] = {...accounts[existingIndex], ...accountData, alias: accounts[existingIndex].alias || ''};
      } else {
        // 添加新账号
        if (accounts.length === 0) {
          accountData.isDefault = true;
        }
        accounts.push(accountData);
      }
      
      chrome.storage.local.set({[hostname]: accounts}, function() {
        console.log('登录信息已保存:', accountData);
        
        // 通知background记录该tab的登录状态
        chrome.runtime.sendMessage({
          action: 'loginStatusChanged',
          isLoggedIn: true,
          account: accountData,
          hostname: hostname
        });
      });
    });
    
  } else if (message.action === 'signOutDetected') {
    console.log('content收到登出通知，转发给background:', message);
    
    // 转发登出通知给background script
    chrome.runtime.sendMessage({
      action: 'signOutDetected',
      domain: message.domain,
      url: message.url
    });
    
  } else if (message.action === 'checkSignOutCooldown') {
    console.log('content收到冷却检查请求，转发给background:', message);
    
    // 转发冷却检查请求给background script
    chrome.runtime.sendMessage({
      action: 'checkSignOutCooldown',
      domain: message.domain
    }, function(response) {
      if (chrome.runtime.lastError || !response) {
        console.warn('冷却检查响应失败，跳过自动登录:', chrome.runtime.lastError?.message);
        window.postMessage({
          action: 'signOutCooldownResult',
          domain: message.domain,
          isInCooldown: false,
          remainingTime: 0,
          requestId: message.requestId,
          error: true
        }, '*');
        return;
      }
      
      // 将background的响应转发回injected script
      window.postMessage({
        action: 'signOutCooldownResult',
        domain: response.domain,
        isInCooldown: response.isInCooldown,
        remainingTime: response.remainingTime,
        requestId: message.requestId
      }, '*');
    });
    
  } else if (message.action === 'loginStatusChecked') {
    console.log('登录状态检查结果:', message);
    
    // 如果未登录，则执行自动登录
    if (!message.isLoggedIn) {
      console.log('用户未登录，开始自动登录');
      window.postMessage({
        action: 'performAutoLogin',
        account: message.account,
        originUrl: message.originUrl
      }, '*');
    } else {
      console.log('用户已登录，跳过自动登录');
      
      // 通知background记录该tab的登录状态
      chrome.runtime.sendMessage({
        action: 'loginStatusChanged',
        isLoggedIn: true,
        account: message.account,
        hostname: window.location.hostname
      }, () => {
        // 在background更新完成后，重新获取账号列表并更新悬浮窗口
        const domain = window.location.hostname;
        chrome.storage.local.get([domain], function(result) {
          const accounts = result[domain] || [];
          if (accounts.length > 1) {
            // 重新检查当前登录状态并更新悬浮窗口
            checkCurrentLoginStatus(accounts);
          }
        });
      });
    }
    
  } else if (message.action === 'getLoginCheckSettings') {
    console.log('获取登录检查设置');
    
    // 获取设置并发送给injected script
    chrome.storage.local.get(['enableLoginCheck', 'customCheckEndpoint', 'enableQrCodeFeature'], function(settings) {
      window.postMessage({
        action: 'loginCheckSettings',
        account: message.account,
        settings: settings,
        originUrl: message.originUrl
      }, '*');
    });
  } else if (message.action === 'autoLoginSuccess') {
    console.log('自动登录成功:', message);
    
    // 通知background记录该tab的登录状态
    chrome.runtime.sendMessage({
      action: 'loginStatusChanged',
      isLoggedIn: true,
      account: message.account,
      hostname: message.hostname,
      uIdToken: message.uIdToken
    }, () => {
      // 在background更新完成后，重新获取账号列表并更新悬浮窗口
      const domain = window.location.hostname;
      chrome.storage.local.get([domain], function(result) {
        const accounts = result[domain] || [];
        if (accounts.length > 1) {
          // 重新检查当前登录状态并更新悬浮窗口
          checkCurrentLoginStatus(accounts);
        }
      });
    });
  } else if (message.action === 'getUIdToken') {
    console.log('页面请求获取uIdToken:', message);
    
    // 获取uIdToken
    const hostname = message.hostname || window.location.hostname;
    chrome.storage.local.get(['uIdToken'], function(result) {
      const tokens = result.uIdToken || {};
      const token = tokens[hostname];
      console.log('找到的uIdToken:', hostname, token);
      
      // 回复给页面
      window.postMessage({
        action: 'uIdTokenResponse',
        requestId: message.requestId,
        success: true,
        token: token,
        hostname: hostname
      }, '*');
    });
  }
});

// 创建账号切换悬浮窗口
let floatingPanel = null;
let currentDomain = null;

function createFloatingAccountSwitcher() {
  const domain = window.location.hostname;
  currentDomain = domain;
  
  // 如果是localhost，创建全局账号切换器
  if (domain === 'localhost') {
    createGlobalAccountSwitcher();
    return;
  }
  
  // 检查当前域名是否有保存的账号
  chrome.storage.local.get([domain], function(result) {
    const accounts = result[domain] || [];
    
    if (accounts.length > 1) {
      // 只有多个账号时才显示切换功能
      createFloatingIcon(accounts);
    }
  });
}

function createFloatingIcon(accounts) {
  // 如果已存在，先移除
  if (floatingPanel) {
    floatingPanel.remove();
    const existingPanel = document.getElementById('account-panel');
    if (existingPanel) existingPanel.remove();
  }
  
  // 检查当前实际登录的账号
  checkCurrentLoginStatus(accounts);
}

// 创建悬浮图标UI
function createFloatingIconUI(accounts, currentAccount = null) {
  // 创建悬浮图标
  const floatingIcon = document.createElement('div');
  floatingIcon.id = 'auto-login-switcher';
  floatingIcon.innerHTML = '👤';
  
  // 从存储中获取保存的位置，如果没有则使用默认位置
  chrome.storage.local.get(['floatingIconPosition'], function(result) {
    const savedPosition = result.floatingIconPosition || {
      right: '2%',
      top: '50%',
      transform: 'none'
    };
    
    // 设置样式
    Object.assign(floatingIcon.style, {
      position: 'fixed',
      width: '45px',
      height: '45px',
      backgroundColor: '#007cff',
      color: 'white',
      borderRadius: '50%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: '18px',
      cursor: 'move',
      zIndex: '999999',
      boxShadow: '0 2px 12px rgba(0,124,255,0.3)',
      transition: 'all 0.3s ease',
      userSelect: 'none'
    });
    
    // 设置位置
    if (savedPosition.left) {
      floatingIcon.style.left = savedPosition.left;
      floatingIcon.style.top = savedPosition.top;
      floatingIcon.style.right = 'auto';
    } else {
      floatingIcon.style.right = savedPosition.right;
      floatingIcon.style.top = savedPosition.top;
      floatingIcon.style.left = 'auto';
    }
    floatingIcon.style.transform = savedPosition.transform || 'none';
    
    // 初始化事件处理器
    initFloatingIconEvents();
  });
  
  function initFloatingIconEvents() {
    // 创建账号列表面板
    const accountPanel = document.createElement('div');
    accountPanel.id = 'account-panel';
    accountPanel.style.display = 'none';
    
    Object.assign(accountPanel.style, {
      position: 'fixed',
      backgroundColor: 'white',
      borderRadius: '8px',
      boxShadow: '0 4px 20px rgba(0,0,0,0.15)',
      zIndex: '999998',
      minWidth: '200px',
      maxWidth: '280px',
      maxHeight: '300px',
      overflowY: 'auto',
      border: '1px solid #e0e0e0'
    });
    
    // 初始化面板位置
    updateAccountPanelPosition();
    
    // 添加标题
    const title = document.createElement('div');
    title.textContent = '切换账号';
    Object.assign(title.style, {
      padding: '12px 16px',
      fontSize: '14px',
      fontWeight: '600',
      color: '#333',
      borderBottom: '1px solid #f0f0f0',
      backgroundColor: '#f8f9fa'
    });
    accountPanel.appendChild(title);
    
    // 添加账号列表
    accounts.forEach(account => {
      const accountItem = document.createElement('div');
      accountItem.className = 'account-switch-item';
      
      // 判断是否为当前登录账号（通过tabLoginStatus而不是isDefault）
      const isCurrent = currentAccount && 
        currentAccount.loginId === account.loginId && 
        currentAccount.domain === account.domain;
      
      accountItem.innerHTML = `
        <div style="padding: 12px 16px; cursor: pointer; transition: background-color 0.2s; border-bottom: 1px solid #f5f5f5;">
          <div style="font-weight: ${isCurrent ? '600' : '500'}; color: ${isCurrent ? '#007cff' : '#333'}; margin-bottom: 4px;">
            (${account.domain}) ${account.loginId}
          </div>
          <div style="font-size: 12px; color: #666;">
            点击切换到此账号
          </div>
        </div>
      `;
      
      // 添加点击事件
      accountItem.addEventListener('click', () => {
        switchToAccount(account);
        hideAccountPanel();
      });
      
      // 悬停效果
      accountItem.addEventListener('mouseenter', () => {
        accountItem.firstElementChild.style.backgroundColor = '#f8f9fa';
      });
      
      accountItem.addEventListener('mouseleave', () => {
        accountItem.firstElementChild.style.backgroundColor = 'transparent';
      });
      
      accountPanel.appendChild(accountItem);
    });
    
    // 更新账号面板位置的函数
    function updateAccountPanelPosition() {
      const iconRect = floatingIcon.getBoundingClientRect();
      const panelWidth = 280; // 面板最大宽度
      const panelHeight = Math.min(300, accounts.length * 60 + 50); // 估算面板高度
      
      // 计算面板位置，优先显示在图标右侧
      let panelLeft = iconRect.right + 2;
      let panelTop = iconRect.top + iconRect.height / 2 - panelHeight / 2;
      
      // 如果右侧空间不足，显示在左侧
      if (panelLeft + panelWidth > window.innerWidth) {
        panelLeft = iconRect.left - panelWidth - 2;
      }
      
      // 如果左侧也不足，居中显示在图标上方或下方
      if (panelLeft < 0) {
        panelLeft = iconRect.left + iconRect.width / 2 - panelWidth / 2;
        
        // 确保不超出左右边界
        panelLeft = Math.max(10, Math.min(panelLeft, window.innerWidth - panelWidth - 10));
        
        // 显示在图标上方或下方
        if (iconRect.top > panelHeight + 12) {
          panelTop = iconRect.top - panelHeight - 2;
        } else {
          panelTop = iconRect.bottom + 2;
        }
      }
      
      // 确保面板不超出上下边界
      panelTop = Math.max(10, Math.min(panelTop, window.innerHeight - panelHeight - 10));
      
      // 应用位置（面板仍然使用像素，因为需要精确控制）
      accountPanel.style.left = panelLeft + 'px';
      accountPanel.style.top = panelTop + 'px';
      accountPanel.style.right = 'auto';
      accountPanel.style.transform = 'none';
    }
    
    // 拖拽相关变量
    let isDragging = false;
    let dragOffset = { x: 0, y: 0 };
    let isClick = true;
  
  // 拖拽功能
  floatingIcon.addEventListener('mousedown', (e) => {
    e.preventDefault();
    isDragging = true;
    isClick = true;
    
    const rect = floatingIcon.getBoundingClientRect();
    dragOffset.x = e.clientX - rect.left;
    dragOffset.y = e.clientY - rect.top;
    
    // 改变样式表示开始拖拽
    floatingIcon.style.cursor = 'grabbing';
    floatingIcon.style.transition = 'none';
    floatingIcon.style.transform = 'scale(1.1)';
    
    // 隐藏账号面板
    hideAccountPanel();
  });
  
  document.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    
    isClick = false; // 如果有移动，就不是点击
    e.preventDefault();
    
    // 计算新位置（转换为百分比）
    const newX = e.clientX - dragOffset.x;
    const newY = e.clientY - dragOffset.y;
    
    // 确保图标不会超出视窗边界
    const maxX = window.innerWidth - 45;
    const maxY = window.innerHeight - 45;
    
    const clampedX = Math.max(0, Math.min(newX, maxX));
    const clampedY = Math.max(0, Math.min(newY, maxY));
    
    // 转换为百分比
    const percentX = (clampedX / window.innerWidth) * 100;
    const percentY = (clampedY / window.innerHeight) * 100;
    
    // 更新位置（使用百分比）
    floatingIcon.style.left = percentX + '%';
    floatingIcon.style.top = percentY + '%';
    floatingIcon.style.right = 'auto';
    floatingIcon.style.transform = 'scale(1.1)';
  });
  
  document.addEventListener('mouseup', () => {
    if (!isDragging) return;
    
    isDragging = false;
    
    // 恢复样式
    floatingIcon.style.cursor = 'move';
    floatingIcon.style.transition = 'all 0.3s ease';
    floatingIcon.style.transform = 'scale(1)';
    
    // 保存新位置到存储（百分比格式）
    const position = {
      left: floatingIcon.style.left,
      top: floatingIcon.style.top,
      right: 'auto',
      transform: 'none'
    };
    
    chrome.storage.local.set({ floatingIconPosition: position }, () => {
      console.log('悬浮图标位置已保存:', position);
    });
    
    // 更新面板位置
    updateAccountPanelPosition();
    
    // 如果是点击而不是拖拽，显示账号面板
    if (isClick) {
      setTimeout(() => {
        showAccountPanel();
      }, 100);
    }
  });

  // 悬浮事件
  floatingIcon.addEventListener('mouseenter', () => {
    if (!isDragging) {
      Object.assign(floatingIcon.style, {
        backgroundColor: '#0056cc'
      });
      showAccountPanel();
    }
  });
  
  floatingIcon.addEventListener('mouseleave', () => {
    if (!isDragging) {
      Object.assign(floatingIcon.style, {
        backgroundColor: '#007cff'
      });
      // 延迟隐藏，给用户时间移动到面板
      setTimeout(() => {
        if (!accountPanel.matches(':hover') && !floatingIcon.matches(':hover')) {
          hideAccountPanel();
        }
      }, 200);
    }
  });
  
  // 面板悬停事件
  accountPanel.addEventListener('mouseenter', () => {
    showAccountPanel();
  });
  
  accountPanel.addEventListener('mouseleave', () => {
    hideAccountPanel();
  });
  
      function showAccountPanel() {
      // 更新面板位置后再显示
      updateAccountPanelPosition();
      accountPanel.style.display = 'block';
    }
  
  function hideAccountPanel() {
    accountPanel.style.display = 'none';
  }
  
    // 监听窗口大小变化，更新面板位置
    window.addEventListener('resize', () => {
      updateAccountPanelPosition();
    });
    
    // 添加到页面
    document.body.appendChild(floatingIcon);
    document.body.appendChild(accountPanel);
    
    floatingPanel = floatingIcon;
  }
}

// 检查当前实际登录状态
async function checkCurrentLoginStatus(accounts) {
  // 从background获取当前tab的登录状态
  chrome.runtime.sendMessage({
    action: 'getCurrentTabLoginStatus'
  }, function(response) {
    const currentAccount = response && response.account ? response.account : null;
    console.log('从background获取当前tab登录状态:', currentAccount);
    
    // 创建悬浮图标，传入当前账号信息
    createFloatingIconUI(accounts, currentAccount);
  });
}

// 尝试获取当前用户信息
async function tryGetCurrentUser() {
  const commonEndpoints = [
    '/api/user/profile',
  ];
  
  for (const endpoint of commonEndpoints) {
    try {
      const response = await fetch(endpoint, {
        method: 'GET',
        credentials: 'include'
      });
      
      if (response.ok) {
        const userData = await response.json();
        if (userData) {
          console.log(`从 ${endpoint} 获取到用户信息:`, userData);
          return userData;
        }
      }
    } catch (error) {
      // 继续尝试下一个端点
      continue;
    }
  }
  
  return null;
}

// 更新账号的当前状态
function updateAccountsCurrentStatus(accounts, currentUserInfo) {
  let hasUpdated = false;
  
  accounts.forEach(account => {
    const wasDefault = account.isDefault;
    account.isDefault = (account.loginId === currentUserInfo.loginId && account.domain === currentUserInfo.domId);
    
    if (account.isDefault !== wasDefault) {
      hasUpdated = true;
    }
  });
  
  if (hasUpdated) {
    // 保存更新后的状态
    const domain = window.location.hostname;
    chrome.storage.local.set({[domain]: accounts}, function() {
      console.log('账号状态已更新');
    });
  }
}

// 更新当前账号状态
function updateCurrentAccount(newCurrentAccount) {
  const domain = window.location.hostname;
  
  chrome.storage.local.get([domain], function(result) {
    let accounts = result[domain] || [];
    
    // 将所有账号的isDefault设为false
    accounts.forEach(acc => {
      acc.isDefault = false;
    });
    
    // 设置新的当前账号为默认
    const targetAccount = accounts.find(acc => acc.loginId === newCurrentAccount.loginId);
    if (targetAccount) {
      targetAccount.isDefault = true;
      console.log('更新当前账号状态:', targetAccount.loginId);
    }
    
    // 保存更新后的账号列表
    chrome.storage.local.set({[domain]: accounts}, function() {
      console.log('当前账号状态已更新');
    });
  });
}

// 切换账号功能
async function switchToAccount(account) {
  console.log('切换到账号:', account.loginId);
  
  try {
    // 显示加载状态
    showSwitchingStatus('正在准备切换账号...');
    
    // 首先取消所有未完成的请求，防止401重定向
    window.postMessage({
      action: 'abortAllRequests'
    }, '*');
    
    // 稍微延迟一下，确保请求取消完成
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // 更新状态显示
    showSwitchingStatus('正在切换账号...');
    await fetch('/api/user/sign-out', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      
    
    // 发送登录请求
    const response = await fetch('/api/user/sign-in', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        domain: account.domain,
        loginId: account.loginId,
        password: account.password
      })
    }).then(res => res.json())
    
    if (response.uIdToken) {
      console.log('账号切换成功');
      showSwitchingStatus('切换成功，正在刷新页面...', 'success');
      
      // 更新当前账号状态
      updateCurrentAccount(account);
      
      // 通知background记录该tab的登录状态
      chrome.runtime.sendMessage({
        action: 'loginStatusChanged',
        isLoggedIn: true,
        account: account,
        hostname: window.location.hostname,
        uIdToken: response.uIdToken,
      }, () => {
        // 在background更新完成后，重新获取账号列表并更新悬浮窗口
        const domain = window.location.hostname;
        chrome.storage.local.get([domain], function(result) {
          const accounts = result[domain] || [];
          if (accounts.length > 1) {
            // 重新检查当前登录状态并更新悬浮窗口
            checkCurrentLoginStatus(accounts);
          }
        });
      });
      
      // 延迟刷新页面
      setTimeout(() => {
        window.location.reload();
      }, 1000);
      
    } else {
      console.error('账号切换失败:', response.status);
      showSwitchingStatus('切换失败，请重试', 'error');
      
      setTimeout(() => {
        hideSwitchingStatus();
      }, 3000);
    }
    
  } catch (error) {
    console.error('账号切换错误:', error);
    showSwitchingStatus('网络错误，请重试', 'error');
    
    setTimeout(() => {
      hideSwitchingStatus();
    }, 3000);
  }
}

// 显示切换状态
function showSwitchingStatus(message, type = 'loading') {
  // 移除现有状态提示
  const existingStatus = document.getElementById('account-switch-status');
  if (existingStatus) {
    existingStatus.remove();
  }
  
  const statusDiv = document.createElement('div');
  statusDiv.id = 'account-switch-status';
  
  const bgColor = type === 'success' ? '#00c751' : type === 'error' ? '#ff3b30' : '#007cff';
  
  Object.assign(statusDiv.style, {
    position: 'fixed',
    top: '2%',
    right: '2%',
    backgroundColor: bgColor,
    color: 'white',
    padding: '12px 20px',
    borderRadius: '8px',
    fontSize: '14px',
    fontWeight: '500',
    zIndex: '1000000',
    boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
    transition: 'all 0.3s ease'
  });
  
  statusDiv.textContent = message;
  document.body.appendChild(statusDiv);
}

// 隐藏切换状态
function hideSwitchingStatus() {
  const statusDiv = document.getElementById('account-switch-status');
  if (statusDiv) {
    statusDiv.style.opacity = '0';
    statusDiv.style.transform = 'translateX(100%)';
    setTimeout(() => {
      statusDiv.remove();
    }, 300);
  }
}

// 监听存储变化，动态更新悬浮窗口
chrome.storage.onChanged.addListener((changes, namespace) => {
  if (namespace === 'local' && currentDomain && changes[currentDomain]) {
    const newAccounts = changes[currentDomain].newValue || [];
    
    if (newAccounts.length > 1) {
      createFloatingIcon(newAccounts);
    } else if (floatingPanel) {
      floatingPanel.remove();
      const accountPanel = document.getElementById('account-panel');
      if (accountPanel) accountPanel.remove();
      floatingPanel = null;
    }
  }
});

// DOM加载完成后创建悬浮窗口
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', createFloatingAccountSwitcher);
} else {
  createFloatingAccountSwitcher();
}

// 创建全局账号切换器（用于localhost）
function createGlobalAccountSwitcher() {
  // 从background获取全局账号列表
  chrome.runtime.sendMessage({ action: 'getGlobalAccounts' }, function(response) {
    if (response && response.success && response.data) {
      console.log('获取到全局账号列表:', response.data);
      createGlobalFloatingIcon(response.data);
    } else {
      console.log('未获取到全局账号列表');
    }
  });
}

// 刷新全局账号列表
function refreshGlobalAccounts() {
  console.log('手动刷新全局账号列表');
  
  // 显示刷新状态
  const refreshBtn = document.getElementById('refresh-global-accounts');
  if (refreshBtn) {
    refreshBtn.textContent = '刷新中...';
    refreshBtn.style.backgroundColor = '#999';
    refreshBtn.disabled = true;
  }
  
  // 通知background重新获取全局账号
  chrome.runtime.sendMessage({ action: 'refreshGlobalAccounts' }, function(response) {
    // 恢复按钮状态
    if (refreshBtn) {
      refreshBtn.textContent = '刷新';
      refreshBtn.style.backgroundColor = '#4CAF50';
      refreshBtn.disabled = false;
    }
    
    if (response && response.success && response.data) {
      console.log('刷新成功，重新创建全局账号切换器');
      // 重新创建悬浮图标
      createGlobalFloatingIcon(response.data);
    } else {
      console.log('刷新失败:', response?.message || '未知错误');
      
      // 显示错误提示
      const errorDiv = document.createElement('div');
      errorDiv.innerHTML = `
        <div style="position: fixed; top: 2%; right: 2%; background: #ff4444; color: white; 
                    padding: 12px 20px; border-radius: 6px; z-index: 1000001; font-size: 14px;">
          刷新失败，请检查网络连接
        </div>
      `;
      document.body.appendChild(errorDiv);
      
      setTimeout(() => {
        errorDiv.remove();
      }, 3000);
    }
  });
}

// 创建全局账号浮动图标
function createGlobalFloatingIcon(globalAccounts) {
  // 如果已存在，先移除
  if (floatingPanel) {
    floatingPanel.remove();
    const existingPanel = document.getElementById('global-account-panel');
    if (existingPanel) existingPanel.remove();
  }
  
  // 创建悬浮图标
  const floatingIcon = document.createElement('div');
  floatingIcon.id = 'global-account-switcher';
  floatingIcon.innerHTML = '🌍';
  
  // 从存储中获取保存的位置
  chrome.storage.local.get(['floatingIconPosition'], function(result) {
    const savedPosition = result.floatingIconPosition || {
      right: '2%',
      top: '50%',
      transform: 'none'
    };
    
    // 设置样式
    Object.assign(floatingIcon.style, {
      position: 'fixed',
      width: '50px',
      height: '50px',
      backgroundColor: '#4CAF50',
      color: 'white',
      borderRadius: '50%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: '20px',
      cursor: 'move',
      zIndex: '999999',
      boxShadow: '0 2px 12px rgba(76,175,80,0.4)',
      transition: 'all 0.3s ease',
      userSelect: 'none'
    });
    
    // 设置位置
    if (savedPosition.left) {
      floatingIcon.style.left = savedPosition.left;
      floatingIcon.style.top = savedPosition.top;
      floatingIcon.style.right = 'auto';
    } else {
      floatingIcon.style.right = savedPosition.right;
      floatingIcon.style.top = savedPosition.top;
      floatingIcon.style.left = 'auto';
    }
    floatingIcon.style.transform = savedPosition.transform || 'none';
    
    // 创建全局账号面板
    const accountPanel = document.createElement('div');
    accountPanel.id = 'global-account-panel';
    accountPanel.style.display = 'none';
    
    Object.assign(accountPanel.style, {
      position: 'fixed',
      backgroundColor: 'white',
      borderRadius: '12px',
      boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
      zIndex: '999998',
      minWidth: '320px',
      maxWidth: '400px',
      maxHeight: '500px',
      overflowY: 'auto',
      border: '1px solid #e0e0e0'
    });
    
         // 计算总统计
    const totalEnvs = globalAccounts.length;
    const totalAccounts = globalAccounts.reduce((sum, env) => sum + env.children.length, 0);
    
     // 添加标题
    const title = document.createElement('div');
    title.innerHTML = `
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <span>账号管理</span>
        <button id="refresh-global-accounts" style="
          background: #4CAF50; color: white; border: none; border-radius: 4px; 
          padding: 4px 8px; font-size: 12px; cursor: pointer; outline: none;
          transition: background-color 0.2s;
        ">刷新</button>
      </div>
    `;
    Object.assign(title.style, {
      padding: '16px 20px',
      fontSize: '16px',
      fontWeight: '600',
      color: '#333',
      borderBottom: '1px solid #f0f0f0',
      backgroundColor: '#f8f9fa',
      borderRadius: '12px 12px 0 0'
    });
    
    // 添加刷新按钮事件
    title.addEventListener('click', (e) => {
      if (e.target.id === 'refresh-global-accounts') {
        e.stopPropagation();
        refreshGlobalAccounts();
      }
    });
    
    // 添加刷新按钮悬停效果
    title.addEventListener('mouseover', (e) => {
      if (e.target.id === 'refresh-global-accounts' && !e.target.disabled) {
        e.target.style.backgroundColor = '#45a049';
      }
    });
    
    title.addEventListener('mouseout', (e) => {
      if (e.target.id === 'refresh-global-accounts' && !e.target.disabled) {
        e.target.style.backgroundColor = '#4CAF50';
      }
    });
    
    accountPanel.appendChild(title);
    
    // 添加搜索框
    const searchContainer = document.createElement('div');
    Object.assign(searchContainer.style, {
      padding: '12px 20px',
      borderBottom: '1px solid #f0f0f0',
      backgroundColor: 'white'
    });
    
    const searchInput = document.createElement('input');
    searchInput.type = 'text';
    searchInput.placeholder = '搜索环境或账号...';
    Object.assign(searchInput.style, {
      width: '100%',
      padding: '8px 12px',
      border: '1px solid #ddd',
      borderRadius: '6px',
      fontSize: '14px',
      outline: 'none'
    });
    
    searchInput.addEventListener('focus', () => {
      searchInput.style.borderColor = '#4CAF50';
    });
    
    searchInput.addEventListener('blur', () => {
      searchInput.style.borderColor = '#ddd';
    });
    
    searchContainer.appendChild(searchInput);
    accountPanel.appendChild(searchContainer);
    
    // 创建账号内容容器
    const accountsContainer = document.createElement('div');
    accountsContainer.id = 'accounts-container';
    accountPanel.appendChild(accountsContainer);
    
         // 渲染账号列表的函数
     function renderGlobalAccounts(accountsToShow = globalAccounts) {
       accountsContainer.innerHTML = '';
       
       if (accountsToShow.length === 0) {
         const noResults = document.createElement('div');
         noResults.textContent = '没有找到匹配的账号';
         Object.assign(noResults.style, {
           padding: '20px',
           textAlign: 'center',
           color: '#999',
           fontSize: '14px'
         });
         accountsContainer.appendChild(noResults);
         return;
       }
       
       accountsToShow.forEach(envGroup => {
         // 环境标题
         const envTitle = document.createElement('div');
         envTitle.textContent = `${envGroup.env}`;
         Object.assign(envTitle.style, {
           padding: '12px 20px 8px',
           fontSize: '14px',
           fontWeight: '600',
           color: '#4CAF50',
           backgroundColor: '#f8f9fa',
           borderBottom: '1px solid #f0f0f0'
         });
         accountsContainer.appendChild(envTitle);
         
         // 账号列表
         envGroup.children.forEach(account => {
           const accountItem = document.createElement('div');
           accountItem.className = 'global-account-item';
           
           accountItem.innerHTML = `
             <div style="padding: 12px 20px; cursor: pointer; transition: background-color 0.2s; border-bottom: 1px solid #f5f5f5;">
               <div style="display: flex; justify-content: space-between; align-items: center;">
                 <div>
                   <div style="font-weight: 500; color: #333; margin-bottom: 4px;">
                     ${account.loginId}
                   </div>
                   <div style="font-size: 12px; color: #666; margin-bottom: 2px;">
                     域: ${account.domain}
                   </div>
                 </div>
               </div>
             </div>
           `;
           
           // 添加点击事件
           accountItem.addEventListener('click', () => {
             handleGlobalAccountClick(account);
             hideGlobalAccountPanel();
           });
           
           // 悬停效果
           accountItem.addEventListener('mouseenter', () => {
             accountItem.firstElementChild.style.backgroundColor = '#f0f8ff';
           });
           
           accountItem.addEventListener('mouseleave', () => {
             accountItem.firstElementChild.style.backgroundColor = 'transparent';
           });
           
           accountsContainer.appendChild(accountItem);
         });
       });
     }
     
     // 搜索功能
     let searchTimeout;
     searchInput.addEventListener('input', () => {
       clearTimeout(searchTimeout);
       searchTimeout = setTimeout(() => {
         const searchTerm = searchInput.value.toLowerCase().trim();
         
         if (!searchTerm) {
           renderGlobalAccounts();
           return;
         }
         
         const filteredAccounts = globalAccounts.map(envGroup => {
           const filteredChildren = envGroup.children.filter(account => {
             return (
               account.loginId.toLowerCase().includes(searchTerm) ||
               account.domain.toLowerCase().includes(searchTerm) ||
               envGroup.env.toLowerCase().includes(searchTerm) ||
               (account.url && account.url.toLowerCase().includes(searchTerm))
             );
           });
           
           return {
             ...envGroup,
             children: filteredChildren
           };
         }).filter(envGroup => envGroup.children.length > 0);
         
         renderGlobalAccounts(filteredAccounts);
       }, 300);
     });
     
     // 初始渲染
     renderGlobalAccounts();
    
    // 更新面板位置
    function updateGlobalAccountPanelPosition() {
      const iconRect = floatingIcon.getBoundingClientRect();
      const panelWidth = 400;
      const panelHeight = Math.min(500, globalAccounts.length * 80 + 100);
      
      let panelLeft = iconRect.right + 10;
      let panelTop = iconRect.top + iconRect.height / 2 - panelHeight / 2;
      
      // 如果右侧空间不足，显示在左侧
      if (panelLeft + panelWidth > window.innerWidth) {
        panelLeft = iconRect.left - panelWidth - 10;
      }
      
      // 如果左侧也不足，居中显示
      if (panelLeft < 0) {
        panelLeft = iconRect.left + iconRect.width / 2 - panelWidth / 2;
        panelLeft = Math.max(10, Math.min(panelLeft, window.innerWidth - panelWidth - 10));
        
        if (iconRect.top > panelHeight + 20) {
          panelTop = iconRect.top - panelHeight - 10;
        } else {
          panelTop = iconRect.bottom + 10;
        }
      }
      
      panelTop = Math.max(10, Math.min(panelTop, window.innerHeight - panelHeight - 10));
      
      accountPanel.style.left = panelLeft + 'px';
      accountPanel.style.top = panelTop + 'px';
    }
    
    // 显示/隐藏面板的函数
    function showGlobalAccountPanel() {
      updateGlobalAccountPanelPosition();
      accountPanel.style.display = 'block';
    }
    
    function hideGlobalAccountPanel() {
      accountPanel.style.display = 'none';
    }
    
    // 拖拽功能
    let isDragging = false;
    let dragOffset = { x: 0, y: 0 };
    let isClick = true;
    
    floatingIcon.addEventListener('mousedown', (e) => {
      e.preventDefault();
      isDragging = true;
      isClick = true;
      
      const rect = floatingIcon.getBoundingClientRect();
      dragOffset.x = e.clientX - rect.left;
      dragOffset.y = e.clientY - rect.top;
      
      floatingIcon.style.cursor = 'grabbing';
      floatingIcon.style.transition = 'none';
      floatingIcon.style.transform = 'scale(1.1)';
      
      hideGlobalAccountPanel();
    });
    
    document.addEventListener('mousemove', (e) => {
      if (!isDragging) return;
      
      isClick = false;
      e.preventDefault();
      
      const newX = e.clientX - dragOffset.x;
      const newY = e.clientY - dragOffset.y;
      
      const maxX = window.innerWidth - 50;
      const maxY = window.innerHeight - 50;
      
      const clampedX = Math.max(0, Math.min(newX, maxX));
      const clampedY = Math.max(0, Math.min(newY, maxY));
      
      // 转换为百分比
      const percentX = (clampedX / window.innerWidth) * 100;
      const percentY = (clampedY / window.innerHeight) * 100;
      
      floatingIcon.style.left = percentX + '%';
      floatingIcon.style.top = percentY + '%';
      floatingIcon.style.right = 'auto';
      floatingIcon.style.transform = 'scale(1.1)';
    });
    
    document.addEventListener('mouseup', () => {
      if (!isDragging) return;
      
      isDragging = false;
      floatingIcon.style.cursor = 'move';
      floatingIcon.style.transition = 'all 0.3s ease';
      floatingIcon.style.transform = 'scale(1)';
      
      // 保存位置
      const position = {
        left: floatingIcon.style.left,
        top: floatingIcon.style.top,
        right: 'auto',
        transform: 'none'
      };
      
      chrome.storage.local.set({ floatingIconPosition: position });
      
      if (isClick) {
        setTimeout(() => {
          showGlobalAccountPanel();
        }, 100);
      }
    });
    
    // 悬停事件
    floatingIcon.addEventListener('mouseenter', () => {
      if (!isDragging) {
        floatingIcon.style.backgroundColor = '#45a049';
        showGlobalAccountPanel();
      }
    });
    
    floatingIcon.addEventListener('mouseleave', () => {
      if (!isDragging) {
        floatingIcon.style.backgroundColor = '#4CAF50';
        setTimeout(() => {
          if (!accountPanel.matches(':hover') && !floatingIcon.matches(':hover')) {
            hideGlobalAccountPanel();
          }
        }, 200);
      }
    });
    
    accountPanel.addEventListener('mouseenter', () => {
      showGlobalAccountPanel();
    });
    
    accountPanel.addEventListener('mouseleave', () => {
      hideGlobalAccountPanel();
    });
    
    // 添加到页面
    document.body.appendChild(floatingIcon);
    document.body.appendChild(accountPanel);
    
    floatingPanel = floatingIcon;
    
    console.log('全局账号切换器已创建');
  });
}

// 处理全局账号点击事件
async function handleGlobalAccountClick(account) {
  console.log('点击全局账号:', account);
  
  // 显示加载状态
  const loadingDiv = document.createElement('div');
  loadingDiv.id = 'global-account-loading';
  loadingDiv.innerHTML = `
    <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); 
                z-index: 1000001; display: flex; align-items: center; gap: 12px;">
      <div style="width: 16px; height: 16px; border: 2px solid #f3f3f3; border-top: 2px solid #4CAF50; 
                  border-radius: 50%; animation: spin 1s linear infinite;"></div>
      <span>正在登录 ${account.loginId}@${account.domain}...</span>
    </div>
    <style>
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    </style>
  `;
  document.body.appendChild(loadingDiv);
  
  try {
    // 获取当前页面的port
    const currentUrl = new URL(window.location.href);
    const currentPort = currentUrl.port
    
    // 调用刷新登录接口
    const refreshLoginUrl = `http://localhost:3700/api/${currentPort - 1}/refreshLogin`;
    console.log('调用刷新登录接口:', refreshLoginUrl);
    
    // 构造请求参数
    const requestBody = {
      domain: account.domain,
      loginId: account.loginId,
      url: account.url
    };
    
    console.log('请求参数:', requestBody);
    
    const response = await fetch(refreshLoginUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    });
    
    if (!response.ok) {
      throw new Error(`刷新登录请求失败: ${response.status} ${response.statusText}`);
    }
    
    const result = await response.json();
    console.log('刷新登录响应:', result);
    
    if (result.success && result.token) {
      // 更新加载状态
      const loadingContent = loadingDiv.querySelector('span');
      if (loadingContent) {
        loadingContent.textContent = `登录成功，正在跳转...`;
      }
      
      // 使用token刷新当前页面
      const currentOrigin = window.location.origin;
      const tokenUrl = `${currentOrigin}?loginToken=${result.token}`;
      
      console.log('使用token跳转:', tokenUrl);
      console.log('登录时间:', result.loginTime);
      
      // 延迟500ms后跳转，让用户看到成功信息
      setTimeout(() => {
        window.location.href = tokenUrl;
      }, 500);
      
    } else {
      throw new Error(result.message || '登录失败：未获取到token');
    }
    
  } catch (error) {
    console.error('刷新登录失败:', error);
    
    // 移除加载状态
    const loading = document.getElementById('global-account-loading');
    if (loading) loading.remove();
    
    // 显示错误提示
    const errorDiv = document.createElement('div');
    errorDiv.innerHTML = `
      <div style="position: fixed; top: 2%; right: 2%; background: #ff4444; color: white; 
                  padding: 12px 20px; border-radius: 6px; z-index: 1000001; font-size: 14px;">
        登录失败: ${error.message}
      </div>
    `;
    document.body.appendChild(errorDiv);
    
    setTimeout(() => {
      errorDiv.remove();
    }, 5000);
  }
}

// 页面卸载前清理
window.addEventListener('beforeunload', function() {
  console.log('内容脚本清理');
  if (floatingPanel) {
    floatingPanel.remove();
    const accountPanel = document.getElementById('account-panel');
    const globalAccountPanel = document.getElementById('global-account-panel');
    if (accountPanel) accountPanel.remove();
    if (globalAccountPanel) globalAccountPanel.remove();
  }
}); 
